﻿/*   
    Copyright (C) 2009 Galaktika Corporation ZAO

    This file is a part of Galaktika.BusinessMonitor
 
    Galaktika.BusinessMonitor is a free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.
      
    You should have received a copy of the GNU General Public License
    along with Galaktika.BusinessMonitor.  If not, see <http://www.gnu.org/licenses/>.
  
    If GPL v.3 is not suitable for your products or company,
    Galaktika Corp provides Galaktika.BusinessMonitor under a flexible commercial license
    designed to meet your specific usage and distribution requirements.
    If you have already obtained a commercial license from Galaktika Corp,
    you can use this file under those license terms.
*/

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Galaktika.BI.Charting;
using Galaktika.BI.Charting.Common;
using Galaktika.BI.Extensibility.Dom;
using Galaktika.BI.Runtime.Services;
using Galaktika.BI.Silverlight.Intermediate;
using Galaktika.BI.Silverlight.Services;
using Ranet.AgOlap.Controls.ToolBar;
using Galaktika.BI.Extensibility;
using Galaktika.BI.Extensibility.ComponentModel;

namespace Galaktika.BI.Silverlight.Controls
{
    public partial class ToolbarControl : UserControl, IBindableObject, IEditableObject, ISizeConstraintsRequestor
    {
        private CustomList<ToolBarButtonItem> m_ToolbarButtons = new CustomList<ToolBarButtonItem>();

        public ToolbarControl()
        {
            InitializeComponent();
            this.toolbar.ItemClick += new ItemClickEventHandler(toolbar_ItemClick);
        }

        //void m_ToolbarButtons_CollectionModified(object sender, ModifiedChangedEventArgs e)
        //{
        //    UpdateToolbar();
        //}

        void toolbar_ItemClick(object sender, ItemClickEventArgs e)
        {
            var buttonItem = e.Item as ToolBarButtonItem;
            IUserTaskManager taskMgr =
                           (IUserTaskManager)this.Context.Services.GetService(typeof(IUserTaskManager));
            if (taskMgr != null && buttonItem != null)
            {
                taskMgr.RunTaskAsync(string.Format(Localization.AppTask_LoadingToolbarButtons, base.Name),
                    state =>
                    {
                        long varValue;
                        long varMask = buttonItem.AValueMask;
                        if (buttonItem.AInGroup)
                        {
                            varValue = varMask;
                        }
                        else
                        {
                            bool newStateChecked = !buttonItem.AChecked;
                            varValue = this.GetButtonVariableValue(buttonItem);
                            if (newStateChecked)
                            {
                                varValue = this.SetValueOfMask(varValue, varMask);

                            }
                            else
                            {
                                varValue = this.ResetValueOfMask(varValue, varMask);
                            }
                        }

                        this.SetButtonVariableValue(buttonItem, varValue);
                        taskMgr.Dispatcher.BeginInvoke(() =>
                                                           {
                                                               this.EndEdit();
                                                           });
                    });
            }
        }

        private void SetButtonVariableValue(ToolBarButtonItem btn, long value)
        {
            if ((btn == null) || (btn.AVariable == string.Empty))
                return;

            if (btn.Context != null)
            {
                var context = btn.Context.Services.GetService<IExecutionContext>();
                if (context != null)
                {
                    // устанавливаю в переменную новое значение
                    context.ModifyVariable(btn.Context, btn.AVariable, value.ToString());
                }
            }
        }

        // Устанавливает значение value по маске mask
        private long SetValueOfMask(long value, long mask)
        {
            return value |= mask;
        }

        // Сбрасывает значение value по маске mask
        private long ResetValueOfMask(long value, long mask)
        {
            return value &= ~(mask);
        }

        private void UpdateToolbar()
        {
            if (this.toolbar.Items.Count > 0)
                this.toolbar.Items.Clear();
            foreach (ToolBarButtonItem button in this.m_ToolbarButtons)
            {
                this.SetButtonPicture(button);
                this.toolbar.AddItem(button);

            }
        }

        /// <summary>
        /// Устанавливает кнопке button изображение
        /// </summary>
        /// <param name="button">Кнопка, для которой устанавливается изображение</param>
        private void SetButtonPicture(ToolBarButtonItem button)
        {
            string assemblyName = button.AChecked ? button.AAssemblyPush : button.AAssemblyRelease;
            string resourceName = button.AChecked ? button.AResNamePush : button.AResNameRelease;

            if (!string.IsNullOrEmpty(resourceName))
            {
                Image im = new Image();
                im.Source =
                    UriResources.GetImage(UriResources.GetResourceString(
                        assemblyName,
                        resourceName.Remove(0, assemblyName.Length + 1)));
                button.Content = im;
            }
            else
            {
                button.Content = button.AText;
            }
        }

        private long GetButtonVariableValue(ToolBarButtonItem btn)
        {
            long varResult = 0;

            if ((btn == null) || (btn.AVariable == string.Empty))
            {
                return varResult;
            }

            if (btn.Context != null)
            {
                IExecutionContext context = (IExecutionContext)btn.Context.Services.GetService(typeof(IExecutionContext));
                if (context != null)
                {
                    BrickVariable var = null;
                    var = context.GetVariable(btn.Context, btn.AVariable, true);
                    if (var != null)
                        long.TryParse(var.CurrentValue, out varResult);
                }
            }
            return varResult;
        }

        private void InitStateAllButtons()
        {
            var tips = new string[this.AToolbarButtons.Count];
             IUserTaskManager taskMgr =
                            (IUserTaskManager) this.Context.Services.GetService(typeof (IUserTaskManager));
             IExecutionContext exe = (IExecutionContext)this.Context.Services.GetService(typeof(IExecutionContext));            
             if (taskMgr != null && exe != null)
             {
                 taskMgr.RunTaskAsync(string.Format(Localization.AppTask_LoadingToolbarButtons, base.Name),
                    state =>
                    {
                        int i = 0;
                        foreach (ToolBarButtonItem buttonItem in this.AToolbarButtons)
                        {
                            string tooltip = exe.Parse(buttonItem.Context, buttonItem.AToolTipText);
                            long varLong = this.GetButtonVariableValue(buttonItem);
                            long varMask = buttonItem.AValueMask;


                            if (buttonItem.AInGroup)
                            {
                                buttonItem.AChecked = (varLong == varMask);
                            }
                            else
                            {
                                buttonItem.AChecked = (varLong & varMask) != 0;
                            }
                            tips[i++] = tooltip;
                        }

                        taskMgr.Dispatcher.BeginInvoke(() =>
                            {
                                int j = 0;
                                foreach (ToolBarButtonItem button in this.AToolbarButtons)
                                {
                                    string tip = tips[j++];
                                    if (button.AShowToolTips && !string.IsNullOrEmpty(tip))
                                    {
                                        ToolTipService.SetToolTip(button, new StyledToolTip() { Content = tip });
                                    }
                                    this.SetButtonPicture(button);
                                }
                            });
                    });
             }

        }



        public CustomList<ToolBarButtonItem> AToolbarButtons
        {
            get
            {                
                 return this.m_ToolbarButtons;
            }
            set
            {
                this.m_ToolbarButtons = new CustomList<ToolBarButtonItem>(value);
                //this.m_ToolbarButtons.CollectionModified += new ModifiedChangedEventHandler(m_ToolbarButtons_CollectionModified);                                
            }
        }

        public bool AUseDefaultLookAndFeel { get; set; }
        public LookAndFeelStyle ALookAndFeelStyle { get; set; }
        public string ASkinName { get; set; }


        #region IBindableObject Members

        private IBindingContext m_Context;
        public IBindingContext Context
        {
            get
            {
                return m_Context;
            }
            set
            {
                m_Context = value;
            }
        }

        private Dictionary<string, IBindingManager> m_Bindings;
        public IDictionary<string, IBindingManager> Bindings
        {
            get
            {
                if (m_Bindings == null)
                {
                    m_Bindings = new Dictionary<string, IBindingManager>();
                }

                return m_Bindings;
            }
        }


        #endregion

        #region IEditableObject Members

        public void BeginEdit()
        {
            
        }

        public void CancelEdit()
        {
            
        }

        public void EndEdit()
        {
            int i=0;
            foreach (var item in m_ToolbarButtons)
            {
                item.ToolBar = this;
                item.Name = "toolbarButton" + i++;
                item.Context = this.Context;
            }
            this.UpdateToolbar();
            this.InitStateAllButtons();
        }

        #endregion

        #region ISizeConstraintsRequestor Members

        public double RequiredMinWidth
        {
            get 
            {
                return double.NaN;
            }
        }

        public double RequiredMinHeight
        {
            get 
            {
                return 44.0;
            }
        }

        #endregion
        

    }
}
